import React, { useImperativeHandle } from "react";
import { Form, Input, TreeSelect, Radio } from 'antd';
import { IOuterCreateOrEditProps } from "vendor/components/pro-table-native";

import { EnumStatus, EnumStatusType } from "../../../../constants";
import {RespDataType} from "../../api";

const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 12 },
};

export const getCreateOrEdit = (menuTree: RespDataType.MenuTree) => {

    const CreateOrEdit: IOuterCreateOrEditProps["CreateOrEditContent"] = React.forwardRef(({rowKey, values}, actionRef) => {
        const [ form ] = Form.useForm();
        useImperativeHandle(actionRef, () => ({
            getFormData: () => new Promise((resolve, reject) => {
                form.validateFields().then((data) => {
                    resolve(data);
                }).catch((e) => {
                    reject(new Error("请检查参数"));
                });
            })
        }));

        return (
            <Form
                {...layout}
                initialValues={{status: EnumStatusType.normal, menuIds:[], ...values}}
                form={form}
            >
                <Form.Item
                    label="角色名称"
                    name="roleName"
                    rules={[{ required: true, message: '请填写角色名称!' }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="状态"
                    name="status"
                    rules={[{ required: true, message: '请填写状态!' }]}
                >
                    <Radio.Group>
                        {EnumStatus.map(({label, value}) => <Radio key={value} value={value}>
                            {label}
                        </Radio>)}
                    </Radio.Group>
                </Form.Item>
                <Form.Item
                    label="菜单"
                    name="menuIds"
                    rules={[{ required: true, message: '请填写菜单!' }]}
                >
                    <TreeSelect {...{
                        treeCheckable: true,
                        allowClear: true,
                        showCheckedStrategy:TreeSelect.SHOW_ALL,
                        treeData: formatMenuTree(menuTree)
                    }} />
                </Form.Item>
                <Form.Item
                    label="备注"
                    name="remark"
                >
                    <Input.TextArea />
                </Form.Item>
            </Form>
        )
    });

    return CreateOrEdit;
}

interface RealTreeNode{
    title: string;
    key: number;
    value: number;
    children: RealTreeNode[];
}

const formatMenuTree = (menuTree: RespDataType.MenuTree): RealTreeNode[] => {
    return menuTree.map((item) => ({
        title: item.label,
        value: item.id,
        key: item.id,
        children: formatMenuTree(item.children || []),
    }))
}

